﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContractorTimesheet.DataModel;
using ContractorTimesheet.Infrastructure;
using ContractorTimesheet.Models;
using ContractorTimesheet.Repository;
using PerpetuumSoft.Knockout;

namespace ContractorTimesheet.Controllers
{
    public class LeavesController : BaseController
    {
        private LeaveRepository repository = new LeaveRepository();

        public ActionResult Index()
        {
            var model = new LeaveEditorModel();

            User user = CurrentSession.User;

            if (user == null || user.IsAdmin)
            {
                model.LeavesInfo.AddRange(LeaveInfo.CreateLeavesInfo(repository.GetAllLeaves()));
            }
            else
            {
                model.LeavesInfo.AddRange(LeaveInfo.CreateLeavesInfo(repository.GetLeaves(user.Id)));
            }

            return View(model.SortByDateDescending());
        }

        public ActionResult AddLeave(LeaveEditorModel model)
        {
            User user = CurrentSession.User;

            Leave newLeave = new Leave(user.Id, model.NewYear, model.NewMonth, model.NewDay, model.NewNote);

            repository.Add(newLeave);

            newLeave.User = user;
            model.LeavesInfo.Add(new LeaveInfo(newLeave));

            model.ResetNewLeave();

            return Json(model.SortByDateDescending());
        }

        public ActionResult DeleteLeave(LeaveEditorModel model, int index)
        {
            LeaveInfo leave = model.LeavesInfo[index];

            repository.DeleteAsync(leave.Id);

            model.LeavesInfo.Remove(leave);

            return Json(model);
        }
    }
}